package com.heima.behavior.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.behavior.mapper.ApReadBehaviorMapper;
import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApReadBehaviorService;
import com.heima.model.behavior.dtos.ReadBehaviorDto;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApReadBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 *
 */
@Service
@Slf4j
public class ApReadBehaviorServiceImpl extends ServiceImpl<ApReadBehaviorMapper, ApReadBehavior>
        implements ApReadBehaviorService {

    @Autowired
    ApBehaviorEntryService apBehaviorEntryService;

    @Override
    public ResponseResult readBehavior(ReadBehaviorDto dto) {

        ApBehaviorEntry apBehaviorEntry = null;
        ApUser user = AppThreadLocalUtils.getUser();

        if (user == null){
            apBehaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(null, dto.getEquipmentId());
        }
        apBehaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(user.getId(), null);

        ApReadBehavior apReadBehavior = getOne(Wrappers.<ApReadBehavior>lambdaQuery()
                .eq(ApReadBehavior::getArticleId, dto.getArticleId())
                .eq(ApReadBehavior::getEntryId, apBehaviorEntry.getId()));



        if (apReadBehavior == null){
            // 第一次阅读添加信息
            apReadBehavior = new ApReadBehavior();
            apReadBehavior.setEntryId(apBehaviorEntry.getId());
            apReadBehavior.setArticleId(dto.getArticleId());
            apReadBehavior.setCount((short)1);
            apReadBehavior.setReadDuration(dto.getReadDuration());
            apReadBehavior.setPercentage(dto.getPercentage());
            apReadBehavior.setLoadDuration((dto.getLoadDuration()));
            apReadBehavior.setCreatedTime(new Date());
            apReadBehavior.setUpdatedTime(new Date());
            save(apReadBehavior);
            return ResponseResult.okResult();
        }else {
            int c = apReadBehavior.getCount() + 1;
            apReadBehavior.setCount((short) c);
            apReadBehavior.setUpdatedTime(new Date());
            updateById(apReadBehavior);
            return ResponseResult.okResult();
        }
    }
}
